package com.kotlin.android.core.managent

import android.app.Activity
import android.app.ActivityManager
import android.content.Context
import com.kotlin.android.core.CoreApp
import java.util.*
import kotlin.system.exitProcess

/**
 * Created by Android Studio.
 * Author: zl
 * Date: 2019/12/7
 * Time: 11:02 AM
 * Activity栈管理
 */
object ActivityStackManager {
    private val activities = Stack<Activity>()

    fun addActivity(activity: Activity) {
        activities.add(activity)
    }

    fun removeActivity(activity: Activity) {
        if (activities.contains(activity)) {
            activities.remove(activity)
            activity.finish()
        }
    }

    fun getTopActivity(): Activity? =
        if (activities.isEmpty()) null else activities[activities.size - 1]

    fun finishAllActivity() {
        activities.indices.reversed()
            .map { activities[it] }
            .forEach {
                if (!it.isFinishing) it.finish()
            }
    }

    /**
     * 完全退出app
     */
    fun exitApp() {
        try {
            finishAllActivity()
            val activityManager =
                CoreApp.instance.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
            activityManager.killBackgroundProcesses(CoreApp.instance.packageName)
            exitProcess(0)
        } catch (e: Exception) {
            exitProcess(1)
        } finally {
            System.gc()
        }
    }
}